package it.example.tinyurl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class TinyActivity extends Activity {

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		
		TextView tv = (TextView) findViewById(R.id.tv);
		
		String mUrl = "http://www.google.com/";
	
		try {
	        HttpClient client = new DefaultHttpClient();
	        String urlTemplate = "http://tinyurl.com/api-create.php?url=%s";
	        String uri = String.format(urlTemplate, URLEncoder.encode(mUrl));
	        HttpGet request = new HttpGet(uri);
	        HttpResponse response = client.execute(request);
	        HttpEntity entity = response.getEntity();
	        InputStream in = entity.getContent();
	        try {
	            StatusLine statusLine = response.getStatusLine();
	            int statusCode = statusLine.getStatusCode();
	            if (statusCode == HttpStatus.SC_OK) {
	                // TODO: Support other encodings
	                String enc = "utf-8";
	                Reader reader = new InputStreamReader(in, enc);
	                BufferedReader bufferedReader = new BufferedReader(reader);
	                String tinyUrl = bufferedReader.readLine();
	                if (tinyUrl != null) {
	                	tv.setText(tinyUrl);
	                    Log.i("URL", tinyUrl);
	                } else {
	                	tv.setText("empty response");
	                    throw new IOException("empty response");
	                }
	            } else {
	                String errorTemplate = "unexpected response: %d";
	                String msg = String.format(errorTemplate, statusCode);
	                throw new IOException(msg);
	            }
	        } finally {
	            in.close();
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } catch (RuntimeException e) {
	        e.printStackTrace();
	    } catch (Error e) {
	        e.printStackTrace();
	    }
	}

}
